﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace uTube.Core.DataTypes.YouTubeUploader
{
	public class YTU_Control : PlaceHolder
	{
		/// <summary>
		/// Gets or sets the options.
		/// </summary>
		/// <value>The options for the control.</value>
		public YTU_Options Options { get; set; }

		/// <summary>
		/// The upload field.
		/// </summary>
		protected HtmlInputFile UploadField;

		/// <summary>
		/// Field for the video id.
		/// </summary>
		protected Literal VideoIdField;

		/// <summary>
		/// Gets the posted file.
		/// </summary>
		/// <value>The posted file.</value>
		public HttpPostedFile PostedFile
		{
			get
			{
				return this.UploadField.PostedFile;
			}
		}

		/// <summary>
		/// Gets or sets the video id.
		/// </summary>
		/// <value>The video id.</value>
		public string VideoId { get; set; }

		/// <summary>
		/// Initialize the control, make sure children are created
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			this.EnsureChildControls();
		}

		/// <summary>
		/// Add the resources (sytles/scripts)
		/// </summary>
		/// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
		}

		/// <summary>
		/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
		/// </summary>
		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			this.EnsureChildControls();

			// Video Id Literal Control
			if (this.VideoIdField == null)
			{
				this.VideoIdField = new Literal();
			}

			this.VideoIdField.ID = this.VideoIdField.ClientID;
			this.VideoIdField.Text = VideoId;
			this.Controls.Add(this.VideoIdField);

			// Upload field as a HtmlInputFile
			if (this.UploadField == null)
			{
				this.UploadField = new HtmlInputFile();
			}

			this.UploadField.ID = this.UploadField.ClientID;
			this.Controls.Add(this.UploadField);
		}

		/// <summary>
		/// Sends server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter"/> object, which writes the content to be rendered on the client.
		/// </summary>
		/// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> object that receives the server control content.</param>
		protected override void Render(HtmlTextWriter writer)
		{
			// render the literal
			this.VideoIdField.RenderControl(writer);

			// render the upload field if no video id exists
			if (string.IsNullOrEmpty(VideoId))
			{
				this.UploadField.RenderControl(writer);
			}
		}
	}
}